package com.own.component.common.util.desensitize;

import com.own.component.common.util.FormUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

/**
 * DesensitizeRule
 *
 * @author chenxueli
 * @date 2022-08-01 22:48:00
 */
@Slf4j
public class DesensitizeRuleStatic {

    /**
     * 名字脱敏
     */
    public static final DesensitizeRule<String> NAME = content -> {
        if (StringUtils.isNotBlank(content)) {
            var name = StringUtils.left(content, 1);
            return StringUtils.rightPad(name, content.length(), "*");
        }
        return content;
    };

    /**
     * 身份证前4位
     */
    public static final DesensitizeRule<String> ID_CARD_FOUR = content -> {
        if (StringUtils.isNotBlank(content)) {
            if (content.length() == 15) {
                return content.replaceAll("(\\w{6})\\w*(\\w)", "$1********$2");
            }
            if (content.length() == 18) {
                return content.replaceAll("(\\w{6})\\w*(\\w)", "$1***********$2");
            }
        }
        return content;
    };

    /**
     * 手机号
     */
    public static final DesensitizeRule<String> PHONE = content -> {
        if (StringUtils.isBlank(content)) {
            return content;
        }
        if (!FormUtil.isPhone(content) || (content.length() != 11)) {
            return content;
        }
        return content.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
    };

    /**
     * 手机号（头部脱敏）
     */
    public static final DesensitizeRule<String> PHONE_PREFIX = content -> {
        if (StringUtils.isBlank(content)) {
            return content;
        }
        if (!FormUtil.isPhone(content) || (content.length() != 11)) {
            return content;
        }
        return content.replaceAll("(\\d{3})\\d{4}(\\d{4})", "*******$2");
    };

    /**
     * 全部打星
     */
    public static final DesensitizeRule<String> STAR_ALL = content -> {
        if (StringUtils.isBlank(content)) {
            return content;
        }
        return StringUtils.leftPad("", content.length(), "*");
    };

    /**
     * 密码脱敏
     */
    public static final DesensitizeRule<String> PASSWORD = STAR_ALL;

    /**
     * 邮箱（@前三位）
     */
    public static final DesensitizeRule<String> EMAIL = content -> {
        if (StringUtils.isBlank(content)) {
            return content;
        }
        var regex = "^([a-zA-Z0-9_-])[a-zA-Z0-9_-]+@([a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+)$";
        var result = content.replaceAll(regex, "$1***@$2");
        if (result.length() == content.length()) {
            return result;
        }
        return result.replace("***", StringUtils.repeat("*", content.length() - result.length() + 3));
    };

}
